package com.woniu.internalcommon.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniu.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    // 盐
    private static final String SIGN = "CPFmsb!@#$$";

    private static final String JWT_KEY_PHONE = "phone";

    // 乘客是1，司机是2
    private static final String JWT_KEY_IDENTITY = "identity";

    // token类型
    private static final String JWT_TOKEN_TYPE = "tokenType";

    private static final String JWT_TOKEN_TIME = "tokenTime";

    // 生成token
    public static String generatorToken(String phone, String identity, String tokenType) {


        String token = JWT.create()
                .setPayload(JWT_KEY_PHONE, phone)
                .setPayload(JWT_KEY_IDENTITY, identity)
                .setPayload(JWT_TOKEN_TYPE, tokenType)
                .setPayload(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString())
                .setKey(SIGN.getBytes())
                .sign();
        return token;
    }

    // 解析token
    public static TokenResult parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        Object phoneObj = jwt.getPayload(JWT_KEY_PHONE);
        Object identityObj = jwt.getPayload(JWT_KEY_IDENTITY);

        String phone = phoneObj == null ? null : phoneObj.toString();
        String identity = identityObj == null ? null : identityObj.toString();

        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    // 校验token
    public static TokenResult checkToken(String token) {
        try {
            boolean verify = JWTUtil.verify(token, SIGN.getBytes());
            if (!verify) {
                return null;
            }
            return parseToken(token);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String token = generatorToken("13910733521", "1", "accessToken");
        System.out.println("生成的token：" + token);
        System.out.println("解析-----------------");
        TokenResult tokenResult = parseToken(token);
        System.out.println("手机号：" + tokenResult.getPhone());
        System.out.println("身份：" + tokenResult.getIdentity());
    }
}
